const shouYehead=["全部","解表剂","泻下剂","和解剂","清热剂","祛暑剂","温里剂","补益剂","固涩剂","安神剂","开窍剂","理气剂","理血剂","治风剂","治燥剂","祛湿剂","祛痰剂","消食剂","驱虫剂","涌吐剂"];
const shouCanghead=["全部","方剂","文献"];
const db=wx.cloud.database();
const _ = db.command;
var allData=[];

// 添加时间格式化函数
export function formatTimestamp(timestamp) {
  if (!timestamp) return '';
  
  // 确保timestamp是数字类型
  const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp;
  
  const date = new Date(ts);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const shouCangdata=[{
  id:1,
  userImg:"../../images/user2.png",
  userName:"张仲景传人2",
  time:"2小时前",
  title:"桂枝汤经典应用",
  neiRong:"桂枝汤由桂枝、白芍、生姜、大枣、甘草组成。主治太阳中风，发热汗出，恶风，脉浮缓。现代应用于感冒、风湿等症。",
  neiRongimg:"../../images/user2-img.png",
  dianZan:"89",
  pingLun:"24",
  shouCang:"42"
}];
const thisUser="张仲景传人1";
const firends_name=[];
Page({
  data: {
    thisUser:thisUser,
    thisUser_msg:{
      name:thisUser,
      img:"../../images/user1.png",
      zan:"100w",
      tieZi:"1",
      guanZhu:"100w",
      fenSi:"100w",
      jieShao:"这是我的介绍"
    },
    title: "岐黄方坛",
    head:shouYehead,
    selectedIndex:0,
    userData:[],
    allData:[],
    myTiezi:[],
    firends_name:firends_name,
    shouYe_shouCanghidden:false,//切换首页隐藏显示
    xiaoXihidden:true,
    mehidden:true,
    foot:[{
      footImg:"../../images/index.png",
      footDaohang:"首页"
    },{
      footImg:"../../images/xing.png",
      footDaohang:"收藏"
    },{
      footImg:"../../images/tongZhi.png",
      footDaohang:"消息"
    },{
      footImg:"../../images/adminUser.png",
      footDaohang:"我的"
    }],
    footIndex:0,
    shouCang:[{
        id:1,
        userImg:"../../images/user2.png",
        userName:"张仲景传人2",
        time:"2小时前",
        title:"桂枝汤经典应用",
        neiRong:"桂枝汤由桂枝、白芍、生姜、大枣、甘草组成。主治太阳中风，发热汗出，恶风，脉浮缓。现代应用于感冒、风湿等症。",
        neiRongimg:"../../images/user2-img.png",
        dianZan:"89",
        pingLun:"24",
        shouCang:"42"
      }],
    firends:[{
        zaiXian:true,
        name:"李东恒学者1",
        img:"../../images/lidongheng.png"
      },{
        zaiXian:true,
        name:"李东恒学者2",
        img:"../../images/lidongheng.png"
      },{
        zaiXian:false,
        name:"李东恒学者3",
        img:"../../images/lidongheng.png"
      },{
        zaiXian:true,
        name:"李东恒学者4",
        img:"../../images/lidongheng.png"
      },{
        zaiXian:false,
        name:"李东恒学者5",
        img:"../../images/lidongheng.png"
    }],
    firend_msgs:[{
      id:0,
      sender_name:"李东恒学者3",
      sender_img:"../../images/lidongheng.png",
      receiver_name:"张仲景传人1",
      receiver_img:"../../images/user1.png",
      content:"问个问题",
      time:"20250907202356"
    },{
      id:1,
      sender_name:"张仲景传人1",
      sender_img:"../../images/user1.png",
      receiver_name:"李东恒学者3",
      receiver_img:"../../images/lidongheng.png",
      content:"好的",
      time:"20250907202556"
    },{
      id:2,
      sender_name:"李东恒学者3",
      sender_img:"../../images/lidongheng.png",
      receiver_name:"张仲景传人1",
      receiver_img:"../../images/user1.png",
      content:"问个问题",
      time:"20250907202356"
    },{
      id:3,
      sender_name:"张仲景传人1",
      sender_img:"../../images/user1.png",
      receiver_name:"李东恒学者3",
      receiver_img:"../../images/lidongheng.png",
      content:"好的",
      time:"20250907202556"
    },{
      id:4,
      sender_name:"李东恒学者3",
      sender_img:"../../images/lidongheng.png",
      receiver_name:"张仲景传人1",
      receiver_img:"../../images/user1.png",
      content:"问个问题",
      time:"20250907202356"
    },{
      id:5,
      sender_name:"张仲景传人1",
      sender_img:"../../images/user1.png",
      receiver_name:"李东恒学者3",
      receiver_img:"../../images/lidongheng.png",
      content:"好的",
      time:"20250907202556"
    },{
      id:6,
      sender_name:"张仲景传人1",
      sender_img:"../../images/user1.png",
      receiver_name:"李东恒学者3",
      receiver_img:"../../images/lidongheng.png",
      content:"好的",
      time:"20250907202556"
    },{
      id:7,
      sender_name:"李东恒学者3",
      sender_img:"../../images/lidongheng.png",
      receiver_name:"张仲景传人1",
      receiver_img:"../../images/user1.png",
      content:"问个问题",
      time:"20250907202356"
    },{
      id:8,
      sender_name:"张仲景传人1",
      sender_img:"../../images/user1.png",
      receiver_name:"李东恒学者3",
      receiver_img:"../../images/lidongheng.png",
      content:"好的",
      time:"20250907202556"
    },{
      id:9,
      sender_name:"李东恒学者3",
      sender_img:"../../images/lidongheng.png",
      receiver_name:"张仲景传人1",
      receiver_img:"../../images/user1.png",
      content:"问个问题",
      time:"20250907202356"
    }]
  },

  getData:function(index){    
    // 根据索引获取分类名称
    const fenLei = shouYehead[index];
    console.log(fenLei)
    // 创建数据库查询对象
    let query = db.collection("fangjiguanli");
    
    // 如果不是"全部"分类，则添加分类过滤条件
    if (fenLei !== "全部") {
      query = query.where({
        fenLei: fenLei
      });
    }
    
    // 继续添加排序、分页等条件并执行查询
    query.orderBy('price', 'desc')
         .skip(0)
         .limit(10)
         .get()
         .then((res)=>{
      // 格式化每条数据中的时间戳
      allData = res.data.map(item => ({
        ...item,
        formattedTime: formatTimestamp(item.time || item.createdAt)
      }));
      this.setData({
        userData: allData
      })
      console.log(allData);
    })
  },

  onLoad: function(e) {
    this.getData(0);

    const firend_msgs = this.data.firend_msgs;
    const uniqueNames = [];
    const nameMap = {}; // 使用对象作为哈希表来快速检查重复
    
    // 正向遍历以保持最新消息在前
    for(var i = firend_msgs.length-1; i>=0; i--) {
      const senderName = firend_msgs[i].sender_name;
      // 检查是否是发给当前用户的消息并且该用户尚未添加
      if(firend_msgs[i].receiver_name === this.data.thisUser && !nameMap[senderName]) {
        nameMap[senderName] = true; // 标记为已添加
        uniqueNames.push(firend_msgs[i]); // 添加整个消息对象
      }
    }
    
    const Tiezi=[];
    for(var i=0;i<allData.length;i++){
      if(allData[i].userName===thisUser){
        Tiezi.push(allData[i]);
      }
    }
    

    this.setData({
      firends_name: uniqueNames,
      myTiezi:Tiezi
    });
  },
  daoHangclick:function(e){
    // 获取点击项的索引
    const index = e.currentTarget.dataset.index;
    this.getData(index);
    // 更新选中索引
    this.setData({
      selectedIndex: index
    });
  },
  footClick:function(e){
    const index = e.currentTarget.dataset.index;

    // 页面回到顶部
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300 // 滚动动画持续时间（毫秒）
    });

    switch(index){
      case 0:
        this.setData({
          head:shouYehead,
          userData:allData,
          shouYe_shouCanghidden:false,
          xiaoXihidden:true,
          mehidden:true,
        })
        break;
      case 1:
        this.setData({
          head:shouCanghead,
          userData:shouCangdata,
          shouYe_shouCanghidden:false,
          xiaoXihidden:true,
          mehidden:true
        })
        break;
      case 2:
        this.setData({
          head:[],
          userData:[],
          shouYe_shouCanghidden:true,
          xiaoXihidden:false,
          mehidden:true
        })
        break;
      case 3:
        this.setData({
          head:[],
          userData:[],
          shouYe_shouCanghidden:true,
          xiaoXihidden:true,
          mehidden:false
        })
        break;
    }
    this.setData({
      footIndex:index,
      selectedIndex:0
    });
  },
  goToxiangQing:function(e){
    // 获取点击项的索引
    const index = e.currentTarget.dataset.index;
    // 获取对应的数据
    const itemData = this.data.userData[index];
    // 跳转到详情页并传递数据
    wx.navigateTo({
      url: `/pages/xiangQing/xiangQing?data=${JSON.stringify(itemData)}`
    });
  },
  goToliaotian:function(e){
    // 获取点击项的索引
    const index = e.currentTarget.dataset.index;
    // 获取对应的数据
    const item = this.data.firend_msgs[index];
    const item_name=item.sender_name;
    const itemData=[];
    itemData.push(item_name);
    for(var i=0;i<this.data.firend_msgs.length;i++){
      if(this.data.firend_msgs[i].sender_name===item_name&&this.data.firend_msgs[i].receiver_name===thisUser||this.data.firend_msgs[i].sender_name===thisUser&&this.data.firend_msgs[i].receiver_name===item_name){
        itemData.push(this.data.firend_msgs[i]);
      }
    }
    // 跳转到详情页并传递数据
    wx.navigateTo({
      url: `/pages/liaoTian/liaoTian?data=${JSON.stringify(itemData)}`
    });
  },
  goTofaBu:function(e){
    wx.navigateTo({
      url: `/pages/faBu/faBu`
    });
  }
})